/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using System.Linq;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside
{
    static class CPBindings
    {
        private static DispatcherTimer blinkTablesOnHoldTimer;
        private static ScrollViewer scrollViewerOpenTables;

        public static ScrollViewer ScrollViewerOpenTables
        {
            get { return CPBindings.scrollViewerOpenTables; }
            set { CPBindings.scrollViewerOpenTables = value; }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static ScrollViewer FindScroll()
        {
            if (scrollViewerOpenTables == null)
            {
                Border scroll_border = VisualTreeHelper.GetChild(Oceanside.ControlPanelWindow.OpenTables, 0) as Border;

                if (scroll_border is Border)
                {
                    scrollViewerOpenTables = scroll_border.Child as ScrollViewer;

                    if (scrollViewerOpenTables is ScrollViewer)
                    {
                        return scrollViewerOpenTables;
                    }
                }
            }
            return scrollViewerOpenTables;
        }

        public static void Init()
        {
            ControlPanelWindow.OpenTables.SelectionChanged +=
                new SelectionChangedEventHandler(listBoxOpenTables_SelectionChanged_NOTHROW);

            ///Used to blink tables that have products are on hold.
            blinkTablesOnHoldTimer = new DispatcherTimer();
            blinkTablesOnHoldTimer.Interval = TimeSpan.FromSeconds(1);
            blinkTablesOnHoldTimer.Tick += new EventHandler(blinkTablesOnHoldTimer_Tick_NOTHROW);
        }

        public static void Refresh()
        {
            PosWindow.RefreshVisibility(PosWindow.PROP_TYPE_ENUM.CP);
        }

        /// <summary>
        /// 
        /// </summary>
        public static void PrepareForScreenChange_NOTHROW()
        {
            try
            {
                Refresh();

                if (SHIFT.Current != null)
                {
                    ControlPanelWindow.OpenTables.ItemsSource = SHIFT.Current.ORDERS.Where(o=>!o.IsClosed);
                }
                else
                {
                    ControlPanelWindow.OpenTables.ItemsSource = null;
                }

                ControlPanelWindow.OpenTables.SelectedItem = null;

                ///If there are no open tables, then there is no reason to start the blink timer
                ///that blinks tables that have items on hold.
                if (ControlPanelWindow.OpenTables.Items.Count != 0)
                {
                    ///Force a refresh first to assure that the tables color updates ASAP.
                    ControlPanelWindow.OpenTables.Items.Refresh();

                    ///Start the timer that blinks tables that are on hold.
                    blinkTablesOnHoldTimer.Start();
                }

                ControlPanelWindow.AssignDataContext(SHIFT.Current);


                if (!Constants.IsQuickServiceMode)
                {
                    NewTableButton b = (NewTableButton)ControlPanelWindow.PanelFunctions.Children[6];

                    if (SHIFT.Current.Role.JOB_CODE.IsBarTender)
                    {
                        b.ButtonLabelText = "New Bar Seat";
                        NTBindings.IsBarSeatMode = true;
                    }
                    else
                    {
                        NTBindings.IsBarSeatMode = false;
                        b.ButtonLabelText = "New Table";
                    }
                }
            }
            catch (Exception ex)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_CPBIND_PREPARE_FOR_SCREEN_CHANGE, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public static void PrepareForScreenLeave_NOTHROW()
        {
            try
            {
                blinkTablesOnHoldTimer.Stop();
            }
            catch (Exception ex)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_CPBIND_PREPARE_FOR_SCREEN_LEAVE, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        static void blinkTablesOnHoldTimer_Tick_NOTHROW(object sender, EventArgs e)
        {
            try
            {
                ///Only refresh when we are actually on the control panel page.
                if (PosWindow.ActiveWindowInstance is Oceanside.ControlPanelWindow)
                {
                    //Loop through all tables and toggle the visibility to blink the table if there are pending products.
                    for (int i = 0; i < ControlPanelWindow.OpenTables.Items.Count; i++)
                    {
                        ORDER order = (ORDER)ControlPanelWindow.OpenTables.Items[i];
                        if (order != null)
                        {
                            if (order.HasProductsOnHold)
                            {
                                if (order.IsVisible == Visibility.Visible)
                                {
                                    order.IsVisible = Visibility.Hidden;
                                }
                                else
                                {
                                    order.IsVisible = Visibility.Visible;
                                }
                            }
                            else
                            {
                                order.IsVisible = Visibility.Visible;
                            }
                        }
                    }
                    ControlPanelWindow.OpenTables.Items.Refresh();
                }
            }
            catch (Exception ex)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_CPBIND_BLINK_TABLES_ON_HOLD_TIMER_TICK, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        static void listBoxOpenTables_SelectionChanged_NOTHROW(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (e.AddedItems.Count != 0)
                {
                    ORDER order = e.AddedItems[0] as ORDER;
                    USER ordersOwner = USER.GetUserById(order.UserId);
                    USER currUser = SHIFT.Current.User;
                    if (SHIFT.Current.UserIsManager() || ordersOwner.Id == currUser.Id)
                    {
                        SHIFT.SelectedOrder = order;

                        POBindings.TableDisplayString = order.TableString;
                        Oceanside.OrderApi.Show();

                        ControlPanelWindow.OpenTables.SelectedIndex = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_CPBIND_OPEN_TABLES_SELECTION_CHANGED, ex);
            }
        }
    }
}
